package utils

import (
	"bytes"
	"encoding/json"
	"gitee.com/yizhisamoye/GoWeChat/entity"
	"io/ioutil"
	"net/http"
)

func CheckWxResp(resp *http.Response) (map[string]interface{}, error) {
	bodyBytes, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}
	result := make(map[string]interface{})
	err = json.Unmarshal(bodyBytes, &result)
	if err != nil {
		return nil, err
	}
	if _, exist := result["errcode"]; exist && int(result["errcode"].(float64)) != 0 {
		wxErr := new(entity.WxErr)
		wxErr.ErrCode = result["errcode"].(float64)
		wxErr.ErrMsg = result["errmsg"].(string)
		return nil, wxErr
	}
	return result, nil
}

func SendJson(url string, data interface{}) (map[string]interface{}, error) {
	bf := bytes.NewBuffer([]byte{})
	jsonEncoder := json.NewEncoder(bf)
	jsonEncoder.SetEscapeHTML(false)
	err := jsonEncoder.Encode(data)
	if err != nil {
		return nil, err
	}
	client := &http.Client{}
	req, _ := http.NewRequest("POST", url, bytes.NewReader(bf.Bytes()))
	resp, err := client.Do(req)
	if err != nil {
		return nil, err
	}
	return CheckWxResp(resp)
}

func GetJson(url string) (map[string]interface{}, error) {
	resp, err := http.Get(url)
	if err != nil {
		return nil, err
	}
	return CheckWxResp(resp)
}
